package com.example.demo.controller;

import com.example.demo.bean.UploadResult;
import com.example.demo.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/oss")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    @ResponseBody
    public UploadResult upload(@RequestParam("file") MultipartFile multipartFile) {
        return fileService.upload(multipartFile);
    }

    @RequestMapping("/download")
    @ResponseBody
    public String download(String url, HttpServletResponse response) {
        boolean download = false;
        try {
            download = fileService.download(url, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (download) {
            return "download success";
        }
        return "download failed";
    }


    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String url) {
        boolean download = fileService.delete(url);
        if (download) {
            return "delete success";
        }
        return "delete failed";
    }
}
